package com.webex.ta.hydra.save;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.mapper.CannotResolveClassException;
import com.webex.ta.hydra.core.Command;
import com.webex.ta.hydra.core.TestPlan;

import java.io.*;
import java.nio.charset.Charset;

/**
 * Created by IntelliJ IDEA.
 * User: vegaz
 * Date: 2010-8-30
 * Time: 10:52:03
 * To change this template use File | Settings | File Templates.
 */
public class SaveService {
    private static String fileEncoding = "UTF-8";

    private static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"<ph>\"?>"; // $NON-NLS-1$

    private static final XStream saver = new XStream(new DomDriver());
    static {
        saver.autodetectAnnotations(true);
        saver.processAnnotations(TestPlan.class);
        saver.processAnnotations(Command.class);
    }
    
    public static void saveTestPlan(TestPlan  tp, OutputStream out) throws IOException {
        OutputStreamWriter outputStreamWriter =
                new OutputStreamWriter(out, getFileEncodingCharset());
        saver.toXML(tp, outputStreamWriter);
		outputStreamWriter.write('\n');// Ensure terminated properly
		outputStreamWriter.close();
    }


    public static TestPlan loadTestPlan(InputStream reader) throws Exception {
		if (!reader.markSupported()) {
			reader = new BufferedInputStream(reader);
		}
		reader.mark(Integer.MAX_VALUE);
		TestPlan tp = null;
		try {
			// Get the InputReader to use
			InputStreamReader inputStreamReader = getInputStreamReader(reader);
			tp = (TestPlan) saver.fromXML(inputStreamReader);
			inputStreamReader.close();
			return tp;
		} catch (CannotResolveClassException e) {
            e.printStackTrace();
//			reader.reset();
//			return OldSaveService.loadSubTree(reader);
            return null;
		} catch (NoClassDefFoundError e) {
//			log.warn("Missing class ", e);
			return null;
		}
	}

    private static void writeXmlHeader(OutputStreamWriter writer) throws IOException {
		// Write XML header if we have the charset to use for encoding
		Charset charset = getFileEncodingCharset();
		if(charset != null) {
			// We do not use getEncoding method of Writer, since that returns
			// the historical name
			String header = XML_HEADER.replaceAll("<ph>", charset.name());
			writer.write(header);
			writer.write('\n');
		}
	}

    private static Charset getFileEncodingCharset() {
		// Check if we have a encoding to use from properties
		if(fileEncoding != null && fileEncoding.length() > 0) {
			return Charset.forName(fileEncoding);
		}
		else {
			// We use the default character set encoding of the JRE
			return null;
		}
	}

    private static InputStreamReader getInputStreamReader(InputStream inStream) {
		// Check if we have a encoding to use from properties
		Charset charset = getFileEncodingCharset();
		if(charset != null) {
			return new InputStreamReader(inStream, charset);
		}
		else {
			// We use the default character set encoding of the JRE
			return new InputStreamReader(inStream);
		}
	}

}
